import axios from 'axios'
import semver from 'semver'
import urlJoin from 'url-join'

export function getDefaultRegistry(origin = false) {
  return origin
    ? 'https://registry.npmjs.org'
    : 'https://registry.npm.taobao.org'
}

export default function getNpmInfo(npmName: string, registry?: string) {
  if (!npmName) {
    return
  }
  const registryUrl = registry || getDefaultRegistry()
  const npmInfoUrl = urlJoin(registryUrl, npmName)
  // eslint-disable-next-line consistent-return
  return axios
    .get(npmInfoUrl)
    .then(res => {
      if (res.status === 200) {
        return res.data
      }
      return null
    })
    .catch(e => {
      return Promise.reject(e)
    })
}

export async function getNpmInfoVersions(npmName: string, registry: string) {
  const data = await getNpmInfo(npmName, registry)
  return (data && Object.keys(data.versions)) || []
}

function getNpmSameVersions(baseVersion: string, versions: string[]) {
  return versions
    .filter((version: string) => semver.satisfies(version, `>=${baseVersion}`))
    .sort((a, b) => {
      return semver.gt(b, a) ? 1 : -1
    })
}
export async function getNpmSameVersion(
  currentVersion: string,
  npmName: string,
  registry: string
) {
  const versions = await getNpmInfoVersions(npmName, registry)
  const newVersions = getNpmSameVersions(currentVersion, versions)
  return newVersions && newVersions.length > 0 ? newVersions[0] : null
}

// 获取当前包的最新版本
export async function getNpmLastedVersion(npmName: string, registry?: string) {
  const data = await getNpmInfo(npmName, registry)
  const latest = data?.['dist-tags']?.latest // 从接口dist-tag中获取最新版本
  return latest
}
